package com.xiaoshu.aop;

import com.xiaoshu.common.CustomException;
import com.xiaoshu.common.Result;
import com.xiaoshu.common.ResultCode;
import com.xiaoshu.common.ResultGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * 功能说明： 全局异常处理类，对 CustomException 和 Exception异常进行统一处理
 * com.xiaoshu.aop
 *
 * <p>
 * Original @Author: deane.jia-贾亮亮,2021/6/15 15:00
 * <p>
 * Copyright (C)2012-2021 小树盛凯科技 All rights reserved.
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 拦截自定义异常
     *
     * @ExceptionHandler 拦截指定的异常
     */
    @ResponseBody
    @ExceptionHandler(CustomException.class)
    public Result notFount(CustomException e) {
        log.error("Business exception:", e);
        return ResultGenerator.genFailResult(e.getMessage());
    }

    /**
     * 拦截未知的异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result notFount(Exception e, HttpServletRequest request) {
        log.error("Unknown exception:", e);
        return ResultGenerator.genFailResult(ResultCode.INTERNAL_SERVER_ERROR, "Unknown exception, please contact the administrator");
    }
}
